package zzps.exeed.plugin.undertow;

import io.undertow.Undertow;
import io.undertow.server.HttpHandler;
import io.undertow.servlet.Servlets;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.DeploymentManager;
import io.undertow.servlet.api.ServletInfo;
import io.undertow.servlet.util.ImmediateInstanceHandle;
import jakarta.servlet.MultipartConfigElement;
import jakarta.servlet.Servlet;
import jakarta.servlet.ServletException;
import org.slf4j.Logger;
import zzps.exeed.kernel.core.Plugin;
import zzps.exeed.kernel.tool.LogTool;
import zzps.exeed.web.ServerProp;
import zzps.exeed.web.WebServer;
import zzps.exeed.web.servlet.ExeedServlet;

public class UndertowWebServer implements WebServer {
    private static Logger logger = LogTool.getLogger();
    ServerProp serverProp;
    Undertow undertow;
    Servlet servlet;

    public UndertowWebServer(ServerProp serverProp, Servlet servlet) {
        this.serverProp = serverProp;
        this.servlet = servlet;
    }

    @Override
    public void start() {
        try {
            undertow = createUndertowServer();
            undertow.start();
            if (logger.isInfoEnabled()){
                logger.info("undertow server has started on port : {}",serverProp.getPort());
            }
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void stop() {
        if (undertow != null){
            undertow.stop();
            if (logger.isInfoEnabled()){
                logger.info("undertow server has stopped");
            }
        }
    }

    private Undertow createUndertowServer() throws ServletException {
        HttpHandler handler = createHttpHandler();
        Undertow.Builder builder = createUndertowBuilder();
        builder.setHandler(handler);
        return builder.build();
    }

    private Undertow.Builder createUndertowBuilder(){
        Undertow.Builder builder = Undertow.builder();
        builder.addHttpListener(serverProp.getPort(),"0.0.0.0");
        return builder;
    }
    private HttpHandler createHttpHandler() throws ServletException {
        DeploymentInfo deployment = Servlets.deployment()
                .setClassLoader(Plugin.class.getClassLoader())
                .setDeploymentName("exeed")
                .setContextPath("/")
                .setDefaultEncoding("utf-8")
                .setDefaultMultipartConfig(new MultipartConfigElement("./"));
        deployment.addServlet(new ServletInfo("exeedServlet",ExeedServlet.class,() -> new ImmediateInstanceHandle<>(servlet)).addMapping("/"));

//        deployment.addServletContainerInitializer(new ServletContainerInitializerInfo(Initializer.class,
//                new ImmediateInstanceFactory<ServletContainerInitializer>(initializer), NO_CLASSES));
        DeploymentManager manager = Servlets.newContainer().addDeployment(deployment);
        manager.deploy();
        return manager.start();
    }
}
